<template>
  <view class="container">
    <!-- 商品列表 -->
    <view class="product-list">
      <div class="tips">商品信息</div>
      <view v-if="productsList && productsList.length > 0">
        <view v-for="(item, index) in productsList" :key="index" class="product-item">
          <view class="product-title">
            <view class="product-info">
              <image class="cover mr-28" :src="item.image" />
              <view>
                <view class="product-name">{{ item.name }}</view>
                <view class="product-desc">款号：{{ item.productCode }}</view>
              </view>
            </view>
            <view class="remove" @click="remove(index)">删除</view>
          </view>
          <view class="spec-row" @click="showSpec(item)">
            <view>规格</view>
            <view class="spec-value">
              <view>{{ item.specList.map(s => s.spec).join(' ')}}</view>
              <image class="chevronright" :src="IMG_URL2 + 'common/chevron-right.svg'" ></image>
            </view>
          </view>

          <view class="price-row">
            <text class="price">价格</text>
            <text class="amount">¥{{ item.price.toFixed(2) }}</text>
          </view>

          <view class="inStockQuantity-row">
            <text>销售数量</text>
            <view class="cart-count flex justify-between items-center mt-10">
              <!-- <button @click="decreaseQuantity(index)" :disabled="item.inStockQuantity <= 1">-</button>
              <text @input="updateQuantity(index, $event)">{{ item.inStockQuantity }}</text>
              <button @click="increaseQuantity(index)">+</button> -->
              <text class="input cart-reduce" @click="decreaseQuantity(index)">-</text>
              <text class="input cart-text">{{ item.inStockQuantity }}</text>
              <text class="input cart-add" @click="increaseQuantity(index)">+</text>
            </view>
          </view>
        </view>
      </view>
      <view v-else>
        <view class="no-products">暂无商品</view>
      </view>
      <view class="flex justify-between items-center mt-10" v-if="productsList && productsList.length > 0">
        <view></view>
        <view class="flex items-center">
          <view class="total-quantity">共{{ totalQuantity }}件，</view>
          <view class="total-price">合计：¥{{ totalAmount }}</view>
        </view>
      </view>
    </view>

    <!-- 继续添加商品按钮 -->
    <view class="add-more">
      <view class="add-more-btn" @click="addMoreProducts">
        <image class="icon" :src="IMG_URL2 + 'shopm/union.svg'"></image>
        继续添加商品
      </view>
    </view>

    <!-- 客户信息 -->
    <view class="customer-info">
      <view>客户信息</view>
      <view class="info-row flex justify-between">
        <view class="flex">
          <text>手机号</text>
          <input type="text" v-model="customerInfo.mobile" placeholder="请输入手机号" />
        </view>
        <view class="search-icon" @click="getUserInfo">
          <image class="icon" :src="IMG_URL2 + 'shopm/refresh.svg'"></image>
        </view>
      </view>

      <view class="info-row" v-if="customerInfo.name">
        <text>姓名</text>
        <input type="text" v-model="customerInfo.name" placeholder="请输入姓名" />
      </view>

      <view class="info-row" v-if="customerInfo.birthday">
        <text>出生日期</text>
        <input type="text" v-model="customerInfo.birthday" placeholder="请输入出生日期" />
      </view>

      <view class="member-tag" v-if="isNewMember">新会员</view>

      <view class="info-row member" v-if="customerInfo.userId">
        <!-- <view>会员卡号：{{ customerInfo.userId }}</view> -->
        <view>已是会员</view>
        <view>余额：{{ customerInfo.balance }}</view>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-methods">
      <text class="section-title">付款方式</text>
      <radio-group @change="onPaymentChange">
        <template v-if="paymentMethods && paymentMethods.length > 0">
          <label class="payment-option" v-for="method in paymentMethods" :key="method.id">
            <view class="payment-left">
              <image class="payment-icon" :src="IMG_URL2 + 'peop/' + method.icon + '.svg'"></image>
              <text>{{ method.name }}</text>
            </view>
            <radio :value="method.id" :checked="selectedPayment === method.id" />
          </label>
        </template>
        <template v-else>
          <view class="no-payment-methods">暂无可用支付方式</view>
        </template>
      </radio-group>
    </view>

    <!-- 底部结算栏 -->
    <view class="footer">
      <view class="total">
        <text>共{{ totalQuantity }}件，合计：</text>
        <text class="total-amount">¥{{ totalAmount }}</text>
      </view>
      <div class="checkout-btn" @click="handleCheckout">下一步</div>
    </view>

    <!-- 扫码收银选择规格弹窗 -->
    <up-popup :show="showSkuPopup" :round="10" mode="bottom" @close="closeSkuPopup" @open="openSkuPopup">
      <view class="product-list1">
        <view class="product-item1">
          <view class="product-main">
            <image class="product-image" :src="currentProduct.image" mode="aspectFill" />
            <view class="product-content">
              <view>
                <view class="product-name">{{ currentProduct.name }}</view>
                <view class="product-price">¥{{ currentProduct.price }}</view>
              </view>
              <view class="product-total">共{{ currentProduct.inStockQuantity }}件</view>
            </view>
          </view>
          <view class="product-variants">
            <view class="variant-item" v-for="(spec, index) in currentProduct.specList" :key="index" @click="selectVariant(spec,currentProduct.productSkuCode)">
              <view class="variant-label">{{ spec.spec }}</view>
              <view class="variant-quantity">×{{ spec.quantity }}</view>
            </view>
          </view>
        </view>
      </view>
    </up-popup>

    
  </view>

</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { IMG_URL2 } from "@/config";
import { shopApi } from "@/api";
import { useExchangeStore } from '@/store/modules/exchange' // Add this import
const productSkuCode = ref("skuCode-3"); // 扫码获取的商品sku
// 商品列表数据
const productsList = ref([]);
const isNewMember = ref(false);
// 客户信息
const customerInfo = ref({
  mobile: "",
  name: "",
  birthday: ""
});

let currentProduct = ref({})
let showSkuPopup = ref(false)

const exchangeStore = useExchangeStore()

// 支付方式
// 支付方式:1-当面支付 2-现金支付 3-余额支付
const paymentMethods = ref([
  { id:1, name: "当面支付", icon: "qrcode" },
  { id: 3, name: "余额支付", icon: "wallet" },
  { id:2, name: "现金支付", icon: "money-circle" }
]);
const selectedPayment = ref(1);

// 计算总数量
const totalQuantity = computed(() => {
  return productsList.value.reduce((total, item) => total + item.inStockQuantity, 0);
});

// 计算总金额
const totalAmount = computed(() => {
  return productsList.value
    .reduce((total, item) => {
      return total + item.price * item.inStockQuantity;
    }, 0)
    .toFixed(2);
});

// 数量调整方法
const decreaseQuantity = (index) => {
  if (productsList.value[index].inStockQuantity > 1) {
    productsList.value[index].inStockQuantity--;
  }
};

const increaseQuantity = (index) => {
  productsList.value[index].inStockQuantity++;
};

const updateQuantity = (index, event) => {
  const newValue = parseInt(event.detail.value);
  if (!isNaN(newValue) && newValue > 0) {
    productsList.value[index].inStockQuantity = newValue;
  }
};
// 定义方法  
function openSkuPopup() {  
  showSkuPopup.value = true;  
}  
  
function closeSkuPopup() {  
  showSkuPopup.value = false; 
} 

const showSpec = (item)=>{
  currentProduct.value = item;
  showSkuPopup.value = true;  
  getShopDetail(item.productSkuCode)
}

const getShopDetail = (code) => {
  shopApi.PRODUCTGETFRONTPRODUCTDETAILBYSKUCODE({
    productSkuCode: code
  }).then((res) => {
    if (res.code != 200) {
      uni.showToast({
        title: res.errMsg,
        icon: "none"
      });
      return;
    }

    let newdata = res.result.skuList
    for (let i = 0; i < newdata.length; i++) {
        newdata[i].newattributeList = resetArray(newdata[i].attributeList,newdata[i])
    }
    
    let newSkuList = []
    newdata.forEach((sku) => {
        newSkuList.push(getSkuItem(sku.newattributeList))
    })

    currentProduct.value = {
      ...res.result,
      productSkuCode: code,
      inStockQuantity: 1,
      specList: newSkuList.flat(),
    };
  });
};

const resetArray = (inputArray,item)=>{
    inputArray.forEach(element => {
        element.num=1
        element.quantity = 0
        element.PDproductSkuId= item.productSkuId
        element.PDskuCode= item.skuCode
        element.PDskuPic= item.skuPic
        element.PDinventory= item.inventory
        element.PDname= item.name
        element.skuImg= item.skuPic
        
    });
    return Object.values(inputArray.reduce((acc, current) => {
            const key = `${current.name}-${current.sort}`;
            acc[key] = current;
            return acc;
        }, {}));
    
}
const getSkuItem= (inputArray)=>{
    const result = [];

    let colorValue = '';
    let sizeValues = [];

    inputArray.forEach(item => {
        if (item.name === '颜色') {
            colorValue = item.value;
        }
        if (item.name === '尺寸') {
            sizeValues.push({sizeValue:item.value,productSkuId:item.PDproductSkuId,skuCode:item.PDskuCode,skuImg:item.PDskuPic});
        }
    });

    const outputArray = sizeValues.map(items =>{
        return {
        color: colorValue,
        size: items.sizeValue,
        spec: `${colorValue} ${items.sizeValue}`,
        productSkuId: items.productSkuId,
        skuCode: items.skuCode,
        skuImg: items.skuImg,
        quantity: 1
    }});
    return outputArray;
}

const selectVariant = (item, productSkuCode) => {
    productsList.value.forEach(product => {
      product.specList.forEach(spec1 => {
        if (spec1.productSkuCode === productSkuCode) {
            spec1.spec = item.spec
        }
      });
    });
    showSkuPopup.value = false;
}

const getUserInfo = () => {
  // 这里可以添加获取用户信息的逻辑
  if (customerInfo.value.mobile=='') {
    uni.showToast({
      title: "请输入手机号",
      icon: "none"
    });
    return;
  }
  shopApi
    .SHOPGETMEMBERLIST({
      currentPage: 0,
      mobile: customerInfo.value.mobile,
      pageSize: 10
    })
    .then((res) => {
      if (res.code != 200) {
        uni.showToast({
          title: res.errMsg,
          icon: "none"
        });
        return;
      }
      const tempItem = res.result.data[0];
      if (!tempItem) {
        isNewMember.value = true;
      }

      if (tempItem) {
        customerInfo.value = tempItem;
      }
    });
};
const remove = (index) => {
  uni.showModal({
    title: "确认删除",
    content: "您确定要删除该商品吗？",
    success: (res) => {
      if (res.confirm) {
        productsList.value.splice(index, 1);
      }
    }
  });
};

// 添加更多商品
const addMoreProducts = () => {
  // 这里可以添加跳转到商品列表页面的逻辑
  // 继续添加应该是基于扫码能力去添加商品
  uni.scanCode({
    success: (res) => {
      // productSkuCode.value = res.result;
      getFrontProductBySkuCode(res.result);
    }
  });
};

// 支付方式变更
const onPaymentChange = (e) => {
  selectedPayment.value = e.detail.value;
};

// 结算方法
const handleCheckout = () => {
  // 验证商品列表
  if (!productsList.value || productsList.value.length === 0) {
    uni.showToast({
      title: '请添加商品',
      icon: 'none'
    });
    return;
  }

  // 验证客户信息
  // if (!customerInfo.value.mobile) {
  //   uni.showToast({
  //     title: '请输入会员手机号',
  //     icon: 'none'
  //   });
  //   return;
  // }
  let ScanData = {
    productsList:productsList.value.map(product => ({
      ...product,
      totalPrice: (product.price * product.inStockQuantity).toFixed(2) // Add total price for each product
    })),
    customerInfo:customerInfo.value,
    totalQuantity:totalQuantity.value,
    totalAmount:totalAmount.value,
    paymentMethod:selectedPayment.value
  }
  exchangeStore.setScanData(ScanData)
  uni.navigateTo({
    url: `/pagesshop/scancodecashier/confirminfo?data=${JSON.stringify(productsList.value)}&totalAmount=${totalAmount.value}`
  });
};
// 扫码收银 - 根据商品规格编码
const getFrontProductBySkuCode = (code) => {
  shopApi.SCANPAYGETFRONTPRODUCTBYSKUCODE({
    productSkuCode: code
  }).then((res) => {
    if (res.code != 200) {
      uni.showToast({
        title: res.errMsg,
        icon: "none"
      });
      return;
    }
    const data = {
      ...res.result,
      productSkuCode: productSkuCode.value,
      inStockQuantity: 1
    };
    productsList.value.push(data);
  })
}
onLoad((options) => {
  if (options.code) {
    productSkuCode.value = options.code; // 扫码读取的数据
    // getShopDetail(options.code);
    getFrontProductBySkuCode(options.code);
  }
});
</script>

<style>
/* 样式保持不变，但添加了新的样式 */
.container {
  padding: 20rpx;
  box-sizing: border-box;
  background: #f5f5f5;
  min-height: 100vh;
}

.product-list {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;

  .tips {
    font-size: 24rpx;
    color: #000;
  }
}
.product-list1 {
padding: 24rpx;
box-sizing: border-box;
.product-item1 {
  padding: 20rpx 0px;
  border-bottom: 2rpx solid #f5f5f5;

  .product-main {
    display: flex;
    margin-bottom: 20rpx;

    .product-image {
      width: 120rpx;
      height: 120rpx;
      background-color: #f5f5f5;
      margin-right: 20rpx;
    }

    .product-content {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .product-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }

      .product-price {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }

      .product-total {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .product-variants {
    .variant-item {
      display: flex;
      justify-content: space-between;
      font-size: 24rpx;
      color: #666;
      margin-bottom: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .variant-quantity {
        color: #999;
      }
    }
  }
}
}

.product-item {
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.product-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: flex;
  justify-content: space-between;

  .product-info {
    display: flex;
    align-items: center;

    .cover {
      width: 48px;
      height: 48px;
      border-radius: 4px;
      margin-right: 10rpx;
    }

    .product-name {
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      color: rgba(44, 44, 44, 1);
    }

    .product-desc {
      font-size: 12px;
      font-weight: 400;
      line-height: 20px;
      color: rgba(0, 0, 0, 0.6);
    }
  }
}

.remove {
  color: rgba(213, 73, 65, 1);
  font-size: 14px;
  font-weight: 400;
  line-height: 22px;

}

.spec-row,
.price-row,
.inStockQuantity-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 28rpx;

  .cart-count {
    .unit-price {
      color: #f00;
    }

    .input {
      display: block;
      text-align: center;
      float: left;
    }

    .cart-reduce {
      width: 44rpx;
      height: 44rpx;
      line-height: 40rpx;
      border-right: none;
      border: 2rpx solid #ededed;
      border-radius: 8rpx 0rpx 0rpx 8rpx;
      font-size: 36rpx;
      color: #cccccc;
    }

    .cart-text {
      width: 44rpx;
      height: 44rpx;
      line-height: 44rpx;
      border-top: 2rpx solid #ededed;
      border-bottom: 2rpx solid #ededed;
      font-size: 28rpx;
    }

    .cart-add {
      width: 44rpx;
      height: 44rpx;
      line-height: 40rpx;
      border-left: none;
      border: 2rpx solid #ededed;
      border-radius: 0rpx 8rpx 8rpx 0rpx;
      font-size: 36rpx;
      color: #cccccc;
    }
  }
}

.spec-value {
  color: #666;
  display: flex;
  align-items: center;

  .chevronright {
    width: 16px;
    height: 16px;
  }
}

.arrow {
  color: #999;
  margin-left: 10rpx;
}

.amount {
  color: rgba(213, 73, 65, 1);
  font-size: 14px;
  font-weight: 400;
  line-height: 22px;
}

.inStockQuantity-adjuster {
  display: flex;
  align-items: center;
}

.inStockQuantity-adjuster button {
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  border: 1px solid #eee;
  background: #fff;
}

.inStockQuantity-adjuster input {
  width: 80rpx;
  height: 60rpx;
  text-align: center;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.add-more {
  background: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.add-more-btn {
  background: none;
  color: rgba(214, 142, 68, 1);
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  .icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 20rpx;
  }
}

.customer-info {
  background: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;

  .search-icon {
    .icon {
      width: 40rpx;
      height: 40rpx;
      /* margin-right: 20rpx; */
    }
  }
}

.info-row text {
  width: 160rpx;
  font-size: 28rpx;
  color: #333;
}

.info-row input {
  flex: 1;
  font-size: 28rpx;
}

.member {
  display: flex;
  align-items: center;
  color: #d68e44;
  justify-content: space-between;
  font-size: 32rpx;
}

.member-tag {
  display: inline-block;
  background: #fff0e5;
  color: #ff6600;
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  box-sizing: border-box;
  border-radius: 4rpx;
  margin-top: 20rpx;
}

.payment-methods {
  background: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  border-radius: 12rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.payment-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.payment-left {
  display: flex;
  align-items: center;
}

.payment-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 10rpx 24rpx 30rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.total-amount {
  color: rgba(214, 142, 68, 1);
  font-size: 32rpx;
  font-weight: bold;
}

.checkout-btn {
  background: rgba(214, 142, 68, 1);
  color: #fff;
  padding: 8rpx 40rpx;
  border-radius: 80rpx;
  font-size: 28rpx;
}

.no-products,
.no-payment-methods {
  text-align: center;
  padding: 20rpx;
  box-sizing: border-box;
  color: #999;
}
</style>
